package com.example.rabbitmqboot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
//自定义实现不可路由消息兜底方法
public class BackBean implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ConnectionFactory connectionFactory;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setConnectionFactory(connectionFactory);
        rabbitTemplate.setReturnsCallback(this);
    }

    //发布确认回调 可以看是否失败 原因
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String msg) {
        String id = correlationData.getId() == null ? "" : correlationData.getId();
        if (ack) {
            log.info("{}交换机收到信息，消息id：{}", correlationData.getReturned().getExchange(), id);
        } else {
            log.warn("{}交换机收到信息失败，原因：{}", correlationData.getReturned().getExchange(), msg);
        }
    }

    @Override
    //只要消息抵达队列 ，以异步方式优先回调 rerunConfirm
    public void returnedMessage(ReturnedMessage returns) {
        log.warn("不可达路由消息描述", returns.getReplyText());
    }
}
